<template>
    <section>
        <!--        添加框
        destroy-on-close
        -->
        <el-dialog title="部门添加" :visible.sync="dialogFormVisible">

            <el-form :model="addForm" :rules="addFormRules" ref="addForm">
                <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="addForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门编号" :label-width="formLabelWidth" prop="sn">
                    <el-input v-model="addForm.sn" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-radio-group v-model="addForm.state">
                        <el-radio :label="1">启动</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门经理" :label-width="formLabelWidth" prop="managerId">
                    <el-select v-model="addForm.managerId" placeholder="请选择部门经理">
                        <el-option v-for="item in employees" :key="item.id" :label="item.username" :value="item.id">

                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="上级部门" :label-width="formLabelWidth">
                    <el-cascader v-model="addForm.parentPath"
                                 :options="options1"
                                 :props="{ checkStrictly: true }"
                                 clearable>
                    </el-cascader>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm('addForm')">取 消</el-button>
                <el-button type="primary" @click="onSubmit('addForm')">确 定</el-button>
            </div>
        </el-dialog>

        <!--高级查询添加-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item>
                    <el-input v-model="depname" placeholder="部门名字"></el-input>
                </el-form-item>

                <el-select v-model="value" clearable placeholder="请选择">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>

                <el-form-item>
                    <el-button type="primary" v-on:click="getUsers">查询</el-button>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>

            </el-form>
        </el-col>
        <!--列表展示-->
        <el-table :data="departmentlist" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" width="60"></el-table-column>
            <el-table-column prop="name" label="部门名字"></el-table-column>
            <el-table-column prop="sn" label="部门编号"></el-table-column>
            <el-table-column prop="state" label="状态">
                <template scope="scope">
                    <span style="color: green" v-if="scope.row.state===1">启用</span>
                    <span style="color: red" v-else-if="scope.row.state===0">禁用</span>
                </template>
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门"></el-table-column>
            <el-table-column prop="manager.username" label="部门经理"></el-table-column>
            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" class="toolbar">

            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>

            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                           :total="total" style="float:right;">
            </el-pagination>
        </el-col>
    </section>
</template>

<script>
    export default {
        name: "Department",
        data() {
            return {

                addFormRules: {
                    //验证规则
                    name: [
                        {required: true, message: '请输入内容', trigger: 'blur'},
                        {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '请输入内容', trigger: 'blur'},
                        {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
                    ],
                    managerId: [
                        {required: true, message: '请选择一个', trigger: 'blur'}
                    ]
                },
                //上级部门
                options1: [],
                //部门经理
                employees: [],
                //禁用启用
                options: [{
                    value: '1',
                    label: '启用'
                }, {
                    value: '0',
                    label: '禁用'
                }],
                //高级查询字段
                value: "",
                depname: '',
                //弹出框的标题
                title: '',
                //列表展示
                departmentlist: [],
                //页面加载
                listLoading: '',
                currentPage: 1,
                pageSize: 5,
                total: 0,
                //选中的数据
                sels: [],
                //dialog显示
                dialogFormVisible: false,
                addForm: {
                    id: '',
                    name: '',
                    sn: '',
                    state: '',
                    managerId: "",
                    parentPath: ""
                },
                formLabelWidth: '120px'
            }
        },
        methods: {
            //重置。点击取消
            resetForm(addForm) {
                // this.$refs[addForm].resetFields();
                this.dialogFormVisible = false
            },
            //添加查询上级部门
            queryParentDept2() {
                this.$http.post("/dept/queryParent").then(res => {
                    // console.log("上级部门：===========")
                    this.options1 = res.data
                    // console.log(this.options1)
                })
            },
            //修改查询上级部门
            queryParentDept(id) {
                this.$http.post("/dept/queryParent/" + id).then(res => {
                    // console.log("上级部门：===========")
                    this.options1 = res.data
                    // console.log(this.options1)
                })
            },
            //查询部门经理
            queryparent() {
                this.$http.post("/emp").then(res => {
                    // console.log(res)
                    this.employees = res.data
                })
            },
            //提交
            onSubmit(addForm) {
                //提交校验,校验成功
                this.$refs[addForm].validate((valid) => {
                    if (valid) {
                        //封装数据
                        //后端接收的是对象 创建部门经理对象
                        this.addForm.manager = {"id": this.addForm.managerId}
                        //创建上级部门对象
                        //选择了上级部门
                        if (this.addForm.parentPath) {
                            //后端接收的是字符串
                            this.addForm.dirPath = this.addForm.parentPath.toString()
                            // console.log(this.addForm.dirPath)
                            //设置上级部门为最后一个
                            this.addForm.parent = {"id": this.addForm.parentPath[this.addForm.parentPath.length - 1]}
                        }
                        // console.log(this.addForm)
                        this.$http.put("/dept", this.addForm).then(res => {
                            // console.log(res)
                            //关闭dialog
                            this.dialogFormVisible = false
                            //加载数据
                            this.loadData()
                        })
                    } else {
                        return false;
                    }
                });

            },
            //高级查询
            getUsers() {
                //跳转到第一页查询
                this.currentPage = 1
                this.loadData()
            },
            //增加
            handleAdd() {
                this.title = "添加";
                //清空规则
                console.log(this.$refs.addForm)
                if (this.$refs.addForm) {
                    this.$refs.addForm.resetFields();
                }

                //清空表单
                for (let i in this.addForm) {
                    // console.log(addFormKey)
                    this.addForm[i] = ""
                }

                // console.log(this.addForm)
                //显示修改框
                this.dialogFormVisible = true;
                //设置默认状态
                this.addForm.state = 1;
                // console.log(this.addForm)
                //查询部门经理
                this.queryparent()
                //查询上级部门
                this.queryParentDept2()
            },
            //修改
            handleEdit: function (index, row) {
                console.log(row);
                this.title = "部门修改";
                //弹出dialog
                this.dialogFormVisible = true;
                //加载部门经理和上级部门
                this.queryParentDept(row.id);
                // this.queryParentDept2();
                this.queryparent();
                //回显数据(一般数据)
                for (let x in this.addForm) {
                    this.addForm[x] = row[x]
                }
                //回显部门经理
                this.addForm.managerId = row.manager.id;
                //回显上级部门，返回数组
                if (row.dirPath) {
                    this.addForm.parentPath = row.dirPath.split(",")
                }
                console.log(this.addForm)
            },
            //删除单条数据
            handleDel(index, row) {  //row行内所有数据
                this.$confirm('此操作将永久删除该数据, 是否继续?', '删除提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {//确认
                    this.$http.delete("/dept/" + row.id).then(res => {
                        console.log(res);
                        let {message, success} = res.data; //解构函数
                        if (success) {
                            this.$message({
                                message: message,
                                type: 'success'
                            });
                            this.loadData()
                        }
                    })
                }).catch(() => {
                    this.$message('已经取消');
                })
            },
            //加载数据
            loadData() {
                let params = {
                    localPage: this.currentPage, //加载默认参数
                    pageSize: this.pageSize,
                    keywords: this.depname,
                    state: this.value

                }
                //请求地址  then请求成功  catch请求失败
                this.$http.post("/dept", params).then(res => {
                    // console.log(res)
                    // this.departmentlist=res.data.data
                    // this.total = res.data.total
                    let {data, totals} = res.data; //解构
                    this.departmentlist = data;
                    this.total = totals;
                }).catch()
            },
            //批量删除
            batchRemove() {
                this.$confirm('此操作将永久删除这些数据, 是否继续?', '删除提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {//确认
                    this.$http.post("/dept/batchRemove", this.sels).then(res => {
                        console.log(res);
                        let {message, success} = res.data; //解构函数
                        if (success) {
                            this.$message({
                                message: message,
                                type: 'success'
                            });
                            this.loadData()
                        }
                    })
                }).catch(() => {
                    this.$message('已经取消');
                })
            },
            //点击分页,更改当前页
            handleCurrentChange(val) {
                // console.log(val)
                this.currentPage = val;
                this.loadData()
            },
            //选择多少行的数据
            selsChange(rows) {
                // console.log(rows)
                this.sels = rows;
            }
        },
        mounted() {
            //加载完毕之后执行
            this.loadData()
        }
    }
</script>

<style scoped>

</style>
